<template>
  <el-form v-if="obj.show" ref="formRuleRef" :model="form" style="margin-top:1em" :class="center?css.center:css.default"
           :rules="formRules">
    <el-form-item label="选择班级" prop="selectClass">
      <el-select popper-class="pop_height" style="width: 35em" v-model="form.selectClass" value-key="id" filterable
                 placeholder="只能为你管理的班级创建考试">
        <el-option v-for="item in obj.manageClassList" :label="item.name" :value="item" :key="item.id"/>
      </el-select>
    </el-form-item>

    <el-form-item label="考试时间" prop="examTime">
      <el-date-picker v-model="form.examTime" type="datetimerange" start-placeholder="开始时间"
                      end-placeholder="结束时间"></el-date-picker>
    </el-form-item>

    <el-form-item label="考试名称" prop="examName">
      <el-input placeholder="最长30个字" v-model="form.examName"></el-input>
    </el-form-item>

    <el-popover placement="right">
      <el-text >及格正确题比例指的是，考生需要做对百分之多少的题才能算合格，默认为60</el-text>
      <template #reference>
        <el-form-item label="及格正确题比例" prop="passScore">
          <el-input placeholder="输入50代表50%，不可超过100，默认60" v-model="form.passScore"></el-input>
        </el-form-item>
      </template>
    </el-popover>

    <el-form-item>
      <div style="width: 100%;display: flex;flex-direction: row;justify-content: center">
        <el-button @click="createExam(formRuleRef)" type="primary" style="width: 39%">创建</el-button>
      </div>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import {onMounted, reactive, ref} from 'vue'
import {Class, User} from "../../types/mytypes";
import {ClassRequest, ExamRequest} from "../../request/MyRequset";
import {UserStore} from "../../store/store";
import {FormInstance, FormRules} from "element-plus";
import {ISODateToMysqlTime} from "../../tools/mysqlTool";

const props = withDefaults(defineProps<{
  center: boolean,
}>(), {
  center: false,
})
const css = reactive({
  center: "form_center",
  default: "form"
})
const formRuleRef = ref<FormInstance>();
const formRules = reactive<FormRules>({
  examName: [
    {required: true, message: "请输入考试名"},
    {min: 3, max: 30, message: "考试名的长度需在3-30之间"},
  ],
  passScore: [
    {
      asyncValidator: (rule, value) => {
        return new Promise((resolve, reject) => {
          if (isNaN(value)) {
            reject("必须是数字")
          } else if (value < 0 || value > 100) {
            reject("范围只能是0-100")
          } else {
            resolve();
          }
        })
      }
    }
  ],
  selectClass: [
    {
      required: true,
      type: "object",
      fields: {id: {type: "number", required: true, message: "还没有选择班级"}},
      message: "请选择班级"
    }
  ],
  examTime: [
    {required: true, message: "请选择考试时间"}
  ]
})
const form = reactive({
  selectClass: {} as Class,
  examName: '',
  passScore: 60,
  examTime: [] as Array<Date>
});
const obj = reactive({
  user: {} as User,
  manageClassList: [] as Array<Class>,
  show: false
})
onMounted(async () => {
  obj.user = UserStore.getUser();
  obj.manageClassList = (await ClassRequest.userGetManageAll(obj.user.id)).data;
  obj.show = true
})
const emit = defineEmits(["error", "close"])

const createExam = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(async (valid) => {
    if (!valid) return;
    let addRes = await ExamRequest.add(
        form.selectClass.id,
        form.examName,
        ISODateToMysqlTime(form.examTime[0].toISOString()),
        ISODateToMysqlTime(form.examTime[1].toISOString()),
        form.passScore,
        obj.user.id
    );
    // console.log(addRes)
    if (addRes.suc) {
      emit("close");
    } else {
      emit("error", addRes.message);
    }
  })
}
</script>

<style scoped lang="scss">
.pop_height {
  height: 100px
}

.form_center {
  display: flex;
  flex-direction: column;
  align-items: center;

  .el-form-item {
    width: 30em;

    .el-form-item__content {
      justify-content: center;
    }
  }
}

.form {
  display: flex;
  flex-direction: column;

  .el-form-item {
    width: 30em;

    .el-form-item__content {
      justify-content: center;
    }
  }
}

</style>